import os
import csv

# --- 配置 ---
# 请将 'your_file.csv' 替换为您的CSV文件的实际路径
csv_file_path = "/data0/lcy/trident/tools/ocr/ocr_results_merged.csv"
# --- 结束配置 ---


def rename_svs_files(csv_path):
    """
    从CSV文件读取数据，并根据 'ocr_name' 重命名 'file_path' 中的文件。
    """
    if not os.path.exists(csv_path):
        print(f"错误：找不到CSV文件: {csv_path}")
        print("请检查 'csv_file_path' 变量是否设置正确。")
        return

    print(f"正在处理CSV文件: {csv_path}...")

    success_count = 0
    fail_count = 0

    try:
        with open(csv_path, mode="r", encoding="utf-8") as f:
            # 使用 DictReader 可以通过列名访问数据，更方便
            reader = csv.DictReader(f)

            for row in reader:
                try:
                    original_file_path = row["file_path"]
                    ocr_name = row["ocr_name"]
                    status = row["status"]

                    # 1. 检查状态是否为 'Success'
                    if status != "Success":
                        print(f"跳过 (状态非Success): {original_file_path}")
                        fail_count += 1
                        continue

                    # 2. 检查原始文件是否存在
                    if not os.path.exists(original_file_path):
                        print(f"跳过 (文件不存在): {original_file_path}")
                        fail_count += 1
                        continue

                    # 3. 构建新的文件路径
                    # 获取原始文件所在的目录
                    original_dir = os.path.dirname(original_file_path)
                    # 构建新的文件名
                    new_file_name = f"{ocr_name}.svs"
                    # 构建完整的新文件路径
                    new_file_path = os.path.join(original_dir, new_file_name)

                    # 4. 检查新文件名是否已存在
                    if os.path.exists(new_file_path):
                        print(f"跳过 (目标文件已存在): {new_file_path}")
                        fail_count += 1
                        continue

                    # 5. 执行重命名
                    os.rename(original_file_path, new_file_path)
                    print(f"成功: {original_file_path} \n  -> {new_file_path}\n")
                    success_count += 1

                except KeyError as e:
                    print(f"错误: CSV文件中缺少必要的列: {e}。请检查CSV表头。")
                    fail_count += 1
                except OSError as e:
                    print(f"错误: 重命名文件时出错 {original_file_path}: {e}")
                    fail_count += 1
                except Exception as e:
                    print(f"处理行 {row} 时发生未知错误: {e}")
                    fail_count += 1

    except FileNotFoundError:
        print(f"错误：找不到CSV文件: {csv_path}")
    except Exception as e:
        print(f"读取CSV文件时发生错误: {e}")

    print("--- 任务完成 ---")
    print(f"成功重命名: {success_count} 个文件")
    print(f"跳过或失败: {fail_count} 个文件")


# --- 运行脚本 ---
if __name__ == "__main__":
    # 确保将 'your_file.csv' 替换为您的CSV文件的实际路径
    # 例如: csv_file_path = '/home/user/data/my_ocr_results.csv'
    if csv_file_path == "your_file.csv":
        print("=" * 50)
        print("请先修改脚本中的 'csv_file_path' 变量！")
        print("=" * 50)
    else:
        rename_svs_files(csv_file_path)
